from django import template
from django.utils.safestring import mark_safe
from django.utils.html import conditional_escape
from licenses.models import License

register = template.Library()


class GetLicenseNode(template.Node):
	'''
		Generic node to get one license, the tag defines the search paramter.
	'''

	@classmethod
	def handle_token(cls, parser, token):
		tokens = token.contents.split()
		if len(tokens) == 4:
			if tokens[2] != 'as':
				raise template.TemplateSyntaxError("Second argument in %s must be 'as'" % tokens[0])
			return cls(
				abbr = tokens[1][1:-1], # TODO: not a safe parser for quotes
				varname = tokens[3],
			)
		else:
			raise template.TemplateSyntaxError("%r tag requires 3 arguments" % tokens[0])

	def __init__(self, abbr = None, varname = None):
		self.varname = varname
		self.abbr = abbr

	def render(self, context):
		try:
			license = License.objects.filter(abbreviation = self.abbr)[0]
		except IndexError:
			license = None
		context[self.varname] = license
		return ''


# TODO: add get_license_by_slug, etc
@register.tag
def get_license_by_abbr(parser, token):
	'''
		Usage: {% get_license_by_abbr "short_name" as varname %}
	'''
	return GetLicenseNode.handle_token(parser, token)


# TODO: ?? put html into template?
@register.filter
def license_link(license):
	'''
		Usage {{ license|license_link }}
	'''
	data = {
		'name': conditional_escape(license.name),
		'url': conditional_escape(license.url),
	}
	return mark_safe('<a rel="license" href="%(url)s">%(name)s</a>' % data)


@register.filter
def license_logo(license):
	'''
		Usage {{ license|license_logo }}
	'''
	data = {
		'name': conditional_escape(license.name),
		'url': conditional_escape(license.url),
		'img': conditional_escape(license.logo),
	}
	return mark_safe('<a rel="license" href="%(url)s"><img src="%(img)s" title="%(name)s" alt="%(name)s" /></a>' % data)
